package querylayer

import (
	"database/sql"
	"encoding/json"
	"fmt"
	"os"
	"strconv"

	"github.com/tendermint/tendermint/libs/rand"
	"github.com/tendermint/tendermint/my_app/utils"
)

type PatientInfo struct {
	Age      int    `json:"Age"`
	Gender   string `json:"Gender"`
	Province string `json:"Province"`
}

type UserData struct {
	UserID       string `json:"UserID"`
	PubKey       string `json:"PubKey"`
	Cert         string `json:"Cert"`
	Role         string `json:"Role"`
	Description  []byte `json:"Description"`
	OTPSecret    []byte `json:"OTPSecret"`
	Time         string `json:"Time"`
	IsRevoked    bool   `json:"IsRevoked"`
	Organization string `json:"Organization"`
}

func (qe *QueryEngine) InsertUserData(user *UserData) error {
	var patientInfo PatientInfo
	err := json.Unmarshal(user.Description, &patientInfo)
	if err != nil {
		return fmt.Errorf("failed to decode user description: %v", err)
	}

	query := `
		INSERT INTO User_table (
			UserID, Organization, Age, Gender, Province
		) VALUES ($1, $2, $3, $4, $5)
	`
	_, err = qe.db.Exec(query,
		user.UserID,
		user.Organization,
		patientInfo.Age,
		patientInfo.Gender,
		patientInfo.Province,
	)
	if err != nil {
		return fmt.Errorf("failed to insert user data: %v", err)
	}

	return nil
}

func GenerateRandomUserValue(db *sql.DB, n int) error {
	for i := 1; i <= n; i++ {
		patientID := strconv.Itoa(i)
		// 随机生成patientInfo
		age := randInt(1, 100)     // 年龄范围为1到100岁
		gender := randGender()     // 随机生成性别
		province := randProvince() // 随机生成省份

		// 构造 PatientInfo 结构体
		patientInfo := PatientInfo{
			Age:      age,
			Gender:   gender,
			Province: province,
		}

		query := `
		Update User_table set Province=$1 where UserID = $2
	`
		_, err := db.Exec(query,
			patientInfo.Province,
			patientID,
		)
		if err != nil {
			return fmt.Errorf("failed to insert user data: %v", err)
		}
	}

	return nil
}

func LoadCovidData(db *sql.DB, n int) error {

	data := make([][]byte, 0)
	for i := 1; i < 1252; i++ {
		//home/chengyuan/group2/archive/COVID/Covid (1).png
		filename := fmt.Sprintf("/home/chengyuan/group2/archive/COVID/Covid (%d).png", i)
		destFile, err := os.Open(filename)
		if err != nil {
			fmt.Println(err)
			continue
		}
		v, err := utils.Colorhistfeature(destFile)
		if err != nil {
			fmt.Println(err)
			return err
		}
		vector, err := utils.Float32ToBinary(v)
		if err != nil {
			fmt.Println(err)
			return err
		}
		data = append(data, vector)
	}

	for i := 1; i < 1230; i++ {
		filename := fmt.Sprintf("/home/chengyuan/group2/archive/non-COVID/Non-Covid (%d).png", i)
		destFile, err := os.Open(filename)
		if err != nil {
			fmt.Println(err)
			return err
		}
		v, err := utils.Colorhistfeature(destFile)
		if err != nil {
			fmt.Println(err)
			continue
		}
		vector, err := utils.Float32ToBinary(v)
		if err != nil {
			fmt.Println(err)
			return err
		}
		data = append(data, vector)
	}
	//======更新数据
	count := 0
	for h := 1; h <= 300; h++ {
		for i := 0; i < 20; i++ {
			if count == len(data) {
				break
			}
			objectId := h*100 + i
			// objectId = 200
			objectIdString := strconv.Itoa(objectId)

			query := `
		Update file_data set eigenvalue=$1 where object_id = $2
	`
			_, err := db.Exec(query,
				data[count],
				objectIdString,
			)
			if err != nil {
				return fmt.Errorf("failed to insert user data: %v", err)
			}
		}
	}

	return nil
}

var provinces = []string{
	"北京市", "天津市", "河北省", "山西省",
	"辽宁省", "吉林省", "黑龙江省", "上海市", "江苏省",
	"浙江省", "安徽省", "福建省", "江西省", "山东省",
	"河南省", "湖北省", "湖南省", "陕西省",
}

// randInt 生成指定范围内的随机整数
func randInt(min, max int) int {
	return min + rand.Intn(max-min+1)
}

// randGender 随机生成性别
func randGender() string {
	if rand.Intn(2) == 0 {
		return "male"
	}
	return "female"
}

// randProvince 随机生成省份
func randProvince() string {
	return provinces[rand.Intn(len(provinces))]
}
